package com.ourcraft.informationcollectionsystem.service.province.recordExamine;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ourcraft.informationcollectionsystem.entity.*;
import com.ourcraft.informationcollectionsystem.mapper.*;
import com.ourcraft.informationcollectionsystem.service.common.addQueryHistory.AddHistoryService;
import com.ourcraft.informationcollectionsystem.service.common.addQueryHistory.QueryHistoryService;
import com.ourcraft.informationcollectionsystem.utils.statusCode.DataReportFormStatus;
import com.ourcraft.informationcollectionsystem.utils.statusCode.HistoryType;
import org.apache.commons.math3.analysis.function.Add;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;

/**
 * RecordExamineServiceImpl provide Record-Examine-related services interface implementation.
 *
 * @author Liu Yiming
 * @since 2023-11-04
 */
@Service
public class RecordExamineServiceImpl implements RecordExamineService{

    @Autowired
    private CompanyMapper companyMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CityMapper cityMapper;

    @Autowired
    private AddHistoryService addHistoryService;

    /**
     * Get the user's role ID from database recording to user ID.
     *
     * @param userId The ID of the user.
     * @return role ID of the user.
     */
    private int getRoleId(int userId) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        User user = userMapper.selectOne(queryWrapper);
        return user.getRoleId();
    }

    /**
     * Get the user's city name from database recording to user ID.
     *
     * @param userId The ID of the user.
     * @return city name of the user.
     */
    private String getCityName(int userId) {
        QueryWrapper<City> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        City city = cityMapper.selectOne(queryWrapper);
        return city.getCityName();
    }

    @Autowired
    QueryHistoryService queryHistoryService;

    /**
     * Get the user's company ID from database recording to user ID.
     *
     * @param userId The ID of the user.
     * @return company ID of the user.
     */
    private int getCompanyId(int userId) {
        QueryWrapper<Company> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        Company company = companyMapper.selectOne(queryWrapper);
        return company.getCompanyId();
    }

    /**
     * Retrieves information of a record recording to user ID
     *
     * @param userId The ID of the user.
     * @return information of the user's record.
     */
    @Override
    public Map<String, Object> getSingleRecord(int userId) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        int companyId = getCompanyId(userId);
        // 根据用户的company ID从数据库中查询其备案信息的全部内容
        QueryWrapper<Company> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("company_id", companyId);
        Company company = companyMapper.selectOne(queryWrapper);
        Map<String, Object> returnData = new HashMap<>();
        // 添加键值对
        Map<String, Object> recordDetailInfo = new HashMap<>();
        recordDetailInfo.put("companyID", company.getCompanyId());
        recordDetailInfo.put("companyCity", company.getCompanyCity());
        recordDetailInfo.put("companyLocation", company.getCompanyLocation());
        recordDetailInfo.put("companyInstCode", company.getCompanyInstCode());
        recordDetailInfo.put("companyChineseName", company.getCompanyChineseName());
        recordDetailInfo.put("companyEnglishName", company.getCompanyEnglishName());
        recordDetailInfo.put("companyNature", company.getCompanyNature());
        recordDetailInfo.put("companyIndustry", company.getCompanyIndustry());
        recordDetailInfo.put("companyBusiness", company.getCompanyBusiness());
        recordDetailInfo.put("companyContacts", company.getCompanyContacts());
        recordDetailInfo.put("companyAddress", company.getCompanyAddress());
        recordDetailInfo.put("companyPostcode", company.getCompanyPostcode());
        recordDetailInfo.put("companyPhone", company.getCompanyPhone());
        recordDetailInfo.put("companyFax", company.getCompanyFax());
        recordDetailInfo.put("companyEmail", company.getCompanyEmail());
        recordDetailInfo.put("companyRecordStatus", company.getCompanyRecordStatus());
        // 格式化最后提交日期
        Date date = getLastSubmitDate(company.getCompanyId());
        String date_str = dateFormat.format(date);
        recordDetailInfo.put("companySubmitTime", date_str);
        returnData.put("recordDetailInfo", recordDetailInfo);
        // 查询该企业备案信息的审核历史记录，添加进返回结果中
        ArrayList<Map<String, Object>> historyQueryResult = queryHistoryService.getCompanyInfoHistory(companyId);
        returnData.put("recordExamineHistory", historyQueryResult);
        return returnData;
    }

    /**
     * Retrieves information of all records recording to user ID
     *
     * @param userId The ID of the user.
     * @return information of list of all records.
     */
    @Override
    public ArrayList<Map<String, Object>> getAllRecords(int userId) {
        ArrayList<Map<String, Object>> data0 = new ArrayList<>();
        QueryWrapper<Company> queryWrapper = new QueryWrapper<>();
        // 如果用户为市用户则设置cityname为用户所在市的名称
        if (getRoleId(userId) == 2) {
            queryWrapper.eq("company_city", getCityName(userId));
        }
        List<CompanyRecordDetail> companyRecordDetailList = companyMapper.selectCompanyRecordDetails();
        if (companyRecordDetailList != null) {
            // 创建日期格式化对象
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            // 对每一个表单
            for (CompanyRecordDetail item : companyRecordDetailList) {
                Map<String, Object> map = new HashMap<>();
                // 添加键值对
                map.put("companyID", item.getCompanyId());
                map.put("companyCity", item.getCompanyCity());
                map.put("companyLocation", item.getCompanyLocation());
                map.put("companyInstCode", item.getCompanyInstCode());
                map.put("companyChineseName", item.getCompanyChineseName());
                map.put("companyEnglishName", item.getCompanyEnglishName());
                map.put("companyNature", item.getCompanyNature());
                map.put("companyIndustry", item.getCompanyIndustry());
                map.put("companyBusiness", item.getCompanyBusiness());
                map.put("companyContacts", item.getCompanyContacts());
                map.put("companyAddress", item.getCompanyAddress());
                map.put("companyPostcode", item.getCompanyPostcode());
                map.put("companyPhone", item.getCompanyPhone());
                map.put("companyFax", item.getCompanyFax());
                map.put("companyEmail", item.getCompanyEmail());
                map.put("companyRecordStatus", item.getCompanyRecordStatus());

                // 格式化最后提交日期
                Date date = item.getLastSubmitDate();
                String date_str;
                if (date == null) {
                    date_str = "";
                } else {
                    date_str = dateFormat.format(date);
                }
                map.put("companySubmitTime", date_str);
                data0.add(map);
            }
            return data0;
        }
        return data0;
    }

    @Autowired
    CompanyInfoHistoryMapper companyInfoHistoryMapper;

    /**
     * Get the last submit date from database recording to companyId.
     *
     * @param companyId The ID of the company.
     * @return last submit date of the company's record.
     */
    private Date getLastSubmitDate(int companyId) {
        // 根据company ID筛选出该企业备案信息的所有历史记录
        QueryWrapper<CompanyInfoHistory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("company_id", companyId);
        List<CompanyInfoHistory> companyInfoHistoryList = companyInfoHistoryMapper.selectList(queryWrapper);
        if (companyInfoHistoryList.isEmpty()) {
            return new Date();
        }
        // 找到最后一次提交的历史记录并返回提交日期
        Date returnDate = companyInfoHistoryList.get(0).getHistoryDate();
        for (CompanyInfoHistory history : companyInfoHistoryList) {
            Date currentDate = history.getHistoryDate();
            if (currentDate.after(returnDate)) {
                returnDate = currentDate;
            }
        }
        return returnDate;
    }

    /**
     * pass the record in request.
     *
     * @param companyId The ID of the company.
     * @return Operation result.
     */
    @Override
    public boolean passRecord(int companyId) {
        // 更新该备案信息的审核状态为通过状态
        var status = HistoryType.PROVINCE_PASS.ordinal();
        Company company = new Company();
        company.setCompanyRecordStatus(status);
        QueryWrapper<Company> wrapper = new QueryWrapper<>();
        wrapper.eq("company_id", companyId);
        // 添加审核通过的历史记录
        addHistoryService.addFilingInfoSubmission(
                companyId,
                -1,
                status,
                "",
                false
        );

        return companyMapper.update(company, wrapper) != 0;
    }

    /**
     * return back the record in request.
     *
     * @param companyId The ID of the company.
     * @param reason The return back operation reason.
     * @param reasonDescription The detail description of the reason “其他”.
     * @return Operation result.
     */
    @Override
    public boolean returnBackRecord(int companyId, String reason, String reasonDescription) {
        // 更新该备案信息的审核状态为退回状态
        var status = HistoryType.PROVINCE_RETURN.ordinal();
        Company company = new Company();
        company.setCompanyRecordStatus(status);
        QueryWrapper<Company> wrapper = new QueryWrapper<>();
        wrapper.eq("company_id", companyId);
        // 添加审核退回的历史记录
        addHistoryService.addFilingInfoSubmission(
                companyId,
                -1,
                status,
                !Objects.equals(reason, "其他") ? reason : reasonDescription,
                false
        );

        return companyMapper.update(company, wrapper) != 0;
    }
}
